import config from './config'
import { $msg } from './message.js'
/**
 * 扫码
 * @returns 
 */
export function $scanCode() {
	return new Promise((resolve, reject) => {
		uni.scanCode({
			success: ({ result }) => resolve(result),
			fail: err => reject(err)
		})
	})
}

/**
 * 获取远程静态文件的绝对路径
 */
export let $getStaticUrl = (url) => config.STATIC_URL + url

/**
 * 回到页面顶部
 * @param {*} duration 
 * @param {*} scrollTop 
 * @returns 
 */
export function $go2Top(duration = 300, scrollTop = 0) {
	return new Promise(resolve => {
		uni.pageScrollTo({
			scrollTop,
			duration,
			success: r => resolve(r)
		})
	})
}

/**
 * 复制内容
 * @param {*} data 
 * @returns 
 */
export function $copy(data, msg = '复制成功') {
	return new Promise(resolve => {
		uni.setClipboardData({
			data,
			showToast: false,
			success: r => {
				$msg(msg)
				resolve(r)
			}
		});
	})
}

/**
 * 显示操作菜单ActionSheet
 * @param {Object} itemList 选项列表
 * @return {i,text} 下标，文本
 * 
    let {i, text } = await this.$showActionSheet(['举报', '删除'])
 */
export function $showAction(itemList) {
	return new Promise((resolve, reject) => {
		uni.showActionSheet({
			itemList,
			success: ({ tapIndex }) => {
				resolve({
					i: tapIndex,
					text: itemList[tapIndex]
				});
			},
			fail() {
				reject()
			}
		})
	})
}

/**
 * 设置标题
 * @param {*} title 
 */
export function $setTitle(title) {
	uni.setNavigationBarTitle({ title })
}

/**
 * 打电话
 */
export function $call(phoneNumber) {
	uni.makePhoneCall({
		phoneNumber,
		fail(e) {
			console.log(e);
			$msg(e?.errMsg)
		}
	})
}

/**
 * 显示地图，传入经纬度
 */
export function $showMap({ lat, lng }) {
	return new Promise((resolve, reject) => {
		uni.openLocation({
			latitude: parseFloat(lat),
			longitude: parseFloat(lng),
			success(e) {
				resolve(e)
			},
			fail(e) {
				reject(e);
			}
		})
	})
}

/**
 * 预览图片
 * */
export function $previewImg(urls, current) {
	if (!Array.isArray(urls)) {
		urls = [urls]
		current = 0
	}
	uni.previewImage({
		urls,
		current,
	})
}